package com.zby.service.imp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zby.common.exception.BlogException;
import com.zby.mapper.LikesMapper;
import com.zby.model.pojo.Article;
import com.zby.model.pojo.Likes;
import com.zby.service.ArticleService;
import com.zby.service.LikeService;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class LikeServiceImp extends ServiceImpl<LikesMapper, Likes> implements LikeService {
    @Autowired
    private ArticleService articleService;

    @Override
    public Integer toggleLike(Long articleId, Integer id) {
//        判断文章是否存在
        Article byId = articleService.getById(articleId);
        if (byId.getId() == null) {
            throw new BlogException(4101, "文章不存在");
        }
        /**
         * 点赞
         **/
        // 每个用户串行点赞
        // 锁必须要包裹住事务方法
        LikeService postThumbService = (LikeService) AopContext.currentProxy();
        synchronized (String.valueOf(id).intern()) {
            return postThumbService.dotogglelike(id, byId.getId());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int dotogglelike(Integer userId, Integer articleId) {
        Likes likes = new Likes();
        likes.setUserId(userId);
        likes.setArticleId(articleId);
        //        查询是否已经点赞
        QueryWrapper<Likes> likesQueryWrapper = new QueryWrapper<>();
        likesQueryWrapper.eq("user_id", userId).eq("article_id", articleId);
        Likes toggleLike = this.getOne(likesQueryWrapper);
        boolean result;
        if (toggleLike != null) {
            result = this.remove(likesQueryWrapper);
            // 已点赞
            if (result) {
                //点赞数减1
                int update = articleService.updateViewLikes(articleId, 1);
                return update;
            } else {
                throw new BlogException(4101, "取消点赞失败");
            }
        } else {
            result = this.save(likes);
            // 未点赞
            if (result) {
                //点赞数加1
                int update = articleService.updateAddViewLikes(articleId, 1);
                return update;
            } else {
                throw new BlogException(4102, "点赞失败");
            }
        }


    }
}
